package com.mathformulas.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Locale;

import com.mathformulas.R;
import com.mathformulas.adapter.NavDrawerExpandableListAdapter;
import com.mathformulas.helper.Global;
import com.mathformulas.viewmodel.NavDrawerItem;

import android.os.Bundle;
import android.os.Handler;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.SearchManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.webkit.WebSettings.ZoomDensity;
import android.widget.ExpandableListView;
import android.widget.Toast;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ExpandableListView.OnGroupClickListener;
import android.widget.SearchView;
import android.widget.SearchView.OnQueryTextListener;

public class MainActivity extends Activity {

	AlertDialog languageDialog;
	private boolean doubleBackToExitPressedOnce = false;
	private final static String LANGUAGE_KEY = "lang_key";

	private int curParentIdx = 0;
	WebView webView;

	private DrawerLayout mDrawerLayout;
	private ExpandableListView mDrawerList;
	private ActionBarDrawerToggle mDrawerToggle;

	// used to store app title
	private CharSequence mTitle;

	private String[] formulasLink;
	// slide menu items
	private String[] navMenuTitles;
	private TypedArray navMenuIcons;

	private ArrayList<NavDrawerItem> navDrawerHeaderItems;
	HashMap<String, String[]> navDrawerChildItems;
	private NavDrawerExpandableListAdapter adapter;

	@SuppressLint("NewApi")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.getWindow().requestFeature(Window.FEATURE_PROGRESS);

		if (savedInstanceState == null)
			initLang();

		setContentView(R.layout.activity_main);

		// preparing list data
		prepareListData();

		init();

		if (savedInstanceState == null) {
			// on first time display view for first nav item
			displayHeaderView(0);
		}

	}

	@SuppressLint("NewApi")
	private void init() {
		mTitle = getTitle();

		webView = (WebView) findViewById(R.id.wvFormulas);
		mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
		mDrawerList = (ExpandableListView) findViewById(R.id.list_slidermenu);

		webView.getSettings().setJavaScriptEnabled(true);
		webView.getSettings().setUseWideViewPort(true);
		webView.getSettings().setLoadWithOverviewMode(true);
		webView.getSettings().setBuiltInZoomControls(true);
		webView.getSettings().setDisplayZoomControls(false);
		webView.getSettings().setDefaultZoom(ZoomDensity.FAR);

		// mDrawerList.setOnItemClickListener(new SlideMenuClickListener());
		mDrawerList.setOnChildClickListener(new OnChildClickListener() {

			@Override
			public boolean onChildClick(ExpandableListView parent, View v,
					int groupPosition, int childPosition, long id) {
				displayChildView(groupPosition, childPosition);
				return false;
			}
		});

		mDrawerList.setOnGroupClickListener(new OnGroupClickListener() {

			@Override
			public boolean onGroupClick(ExpandableListView parent, View v,
					int groupPosition, long id) {
				// displayHeaderView(groupPosition);
				curParentIdx = groupPosition;
				displayHeaderView(groupPosition);
				return false;
			}
		});

		// setting the nav drawer list adapter
		adapter = new NavDrawerExpandableListAdapter(getApplicationContext(),
				navDrawerHeaderItems, navDrawerChildItems);
		mDrawerList.setAdapter(adapter);

		// enabling action bar app icon and behaving it as toggle button
		getActionBar().setDisplayHomeAsUpEnabled(true);
		getActionBar().setHomeButtonEnabled(true);

		mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
				R.drawable.ic_drawer, // nav menu toggle icon
				R.string.app_name, // nav drawer open - description for
									// accessibility
				R.string.app_name // nav drawer close - description for
									// accessibility
		) {
			public void onDrawerClosed(View view) {
				getActionBar().setTitle(mTitle);
				// calling onPrepareOptionsMenu() to show action bar icons
				invalidateOptionsMenu();
			}

			public void onDrawerOpened(View drawerView) {
				// getActionBar().setTitle(mDrawerTitle);
				// calling onPrepareOptionsMenu() to hide action bar icons
				invalidateOptionsMenu();
			}
		};
		mDrawerLayout.setDrawerListener(mDrawerToggle);

		// Strings to Show In Dialog with Radio Buttons
		final CharSequence[] items = getResources().getStringArray(
				R.array.language_items);

		// Creating and Building the Dialog
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(R.string.dialog_language_title);
		builder.setPositiveButton(R.string.dialog_language_btn_cancel,
				new OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				});

		builder.setSingleChoiceItems(items, -1,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int item) {

						switch (item) {
						case 0:
							changeLanguage(Global.ENG);
							break;
						case 1:
							changeLanguage(Global.VI);
							break;
						case 2:
							// Your code when 3rd option seletced
							break;
						case 3:
							// Your code when 4th option seletced
							break;

						}
						displayHeaderView(0);
						languageDialog.dismiss();
					}

				});
		languageDialog = builder.create();

	}

	private void initLang() {
		// init language
		SharedPreferences prfs = getSharedPreferences("com.mathformulas",
				Context.MODE_PRIVATE);
		String lang = prfs.getString(MainActivity.LANGUAGE_KEY, "eng");
		setLocation(lang);

		Global.setCurrentLanguage(lang);
	}

	private void prepareListData() {
		// load slide menu items
		navMenuTitles = getResources().getStringArray(
				R.array.nav_drawer_header_items);

		formulasLink = getResources().getStringArray(R.array.link_formulas);

		// nav drawer icons from resources
		navMenuIcons = getResources()
				.obtainTypedArray(R.array.nav_drawer_icons);

		// Recycle the typed array
		navMenuIcons.recycle();

		navDrawerHeaderItems = new ArrayList<NavDrawerItem>();
		navDrawerChildItems = new HashMap<String, String[]>();

		// Adding header data
		// Hinh hoc
		navDrawerHeaderItems.add(new NavDrawerItem(navMenuIcons.getResourceId(
				0, -1), navMenuTitles[0]));
		// Đại số
		navDrawerHeaderItems.add(new NavDrawerItem(navMenuIcons.getResourceId(
				1, -1), navMenuTitles[1]));
		// Lượng giác
		navDrawerHeaderItems.add(new NavDrawerItem(navMenuIcons.getResourceId(
				2, -1), navMenuTitles[2]));
		// Phương trình
		navDrawerHeaderItems.add(new NavDrawerItem(navMenuIcons.getResourceId(
				3, -1), navMenuTitles[3]));
		// Hình học giải tích
		navDrawerHeaderItems.add(new NavDrawerItem(navMenuIcons.getResourceId(
				4, -1), navMenuTitles[4]));
		// Đạo hàm vi phân
		navDrawerHeaderItems.add(new NavDrawerItem(navMenuIcons.getResourceId(
				5, -1), navMenuTitles[5]));
		// Tích phân
		navDrawerHeaderItems.add(new NavDrawerItem(navMenuIcons.getResourceId(
				6, -1), navMenuTitles[6]));
		// Đổi đơn vị
		navDrawerHeaderItems.add(new NavDrawerItem(navMenuIcons.getResourceId(
				7, -1), navMenuTitles[7]));
		// Yêu thích
		navDrawerHeaderItems.add(new NavDrawerItem(navMenuIcons.getResourceId(
				8, -1), navMenuTitles[8]));
		// Giới thiệu
		// navDrawerHeaderItems.add(new
		// NavDrawerItem(navMenuIcons.getResourceId(
		// 9, -1), navMenuTitles[9]));

		// Adding child data
		String[] hinhHoc = getResources().getStringArray(
				R.array.childs_hinh_hoc);
		String[] daiSo = getResources().getStringArray(R.array.childs_dai_so);
		String[] luongGiac = getResources().getStringArray(
				R.array.childs_luong_giac);
		String[] phuongTrinh = getResources().getStringArray(
				R.array.childs_phuong_trinh);
		String[] hhGiaiTich = getResources().getStringArray(
				R.array.childs_giai_tich);
		String[] dhViPhan = getResources().getStringArray(
				R.array.childs_dao_ham_vi_phan);
		String[] tichPhan = getResources().getStringArray(
				R.array.childs_tich_phan);
		String[] doiDonVi = getResources().getStringArray(
				R.array.childs_doi_don_vi);
		String[] yeuThich = getResources().getStringArray(
				R.array.childs_yeu_thich);

		navDrawerChildItems
				.put(navDrawerHeaderItems.get(0).getTitle(), hinhHoc);
		navDrawerChildItems.put(navDrawerHeaderItems.get(1).getTitle(), daiSo);
		navDrawerChildItems.put(navDrawerHeaderItems.get(2).getTitle(),
				luongGiac);
		navDrawerChildItems.put(navDrawerHeaderItems.get(3).getTitle(),
				phuongTrinh);
		navDrawerChildItems.put(navDrawerHeaderItems.get(4).getTitle(),
				hhGiaiTich);
		navDrawerChildItems.put(navDrawerHeaderItems.get(5).getTitle(),
				dhViPhan);
		navDrawerChildItems.put(navDrawerHeaderItems.get(6).getTitle(),
				tichPhan);
		navDrawerChildItems.put(navDrawerHeaderItems.get(7).getTitle(),
				doiDonVi);
		navDrawerChildItems.put(navDrawerHeaderItems.get(8).getTitle(),
				yeuThich);
	}

	/**
	 * Slide menu item click listener
	 * */

	/* *
	 * Called when invalidateOptionsMenu() is triggered
	 */
	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		// if nav drawer is opened, hide the action items
		boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
		menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
		return super.onPrepareOptionsMenu(menu);
	}

	/**
	 * Diplaying fragment view for selected nav drawer list item
	 * */
	private void displayHeaderView(int position) {

		curParentIdx = position;
		// update selected item and title, then close the drawer
		mDrawerList.setItemChecked(position, true);
		mDrawerList.setSelection(position);
		setTitle(navMenuTitles[position]);

		// update the main content by replacing fragments
		webView.setWebChromeClient(new WebChromeClient() {
			public void onProgressChanged(WebView view, int progress) {
				MainActivity.this.setProgress(progress * 100);

			}
		});

		webView.setWebViewClient(new WebViewClient() {
			@Override
			public void onReceivedError(WebView view, int errorCode,
					String description, String failingUrl) {
				// Handle the error
			}

			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				view.loadUrl(url);
				return true;
			}

			@Override
			public void onPageFinished(WebView view, String url) {
				super.onPageFinished(view, url);
				if (Global.getCurrentLanguage() != Global.ENG)
					webView.loadUrl("javascript:translate('"
							+ Global.getCurrentLanguage() + "', null)");
			}
		});

		webView.loadUrl("file:///android_asset/" + formulasLink[position]);
	}

	private void displayChildView(int parentIdx, int childIdx) {
		String js = "javascript:goto(" + childIdx + ")";
		callJavascript(parentIdx, js);
		mDrawerLayout.closeDrawer(mDrawerList);
	}

	private void displaySearch(String key) {
		String js = "javascript:searchQuery('" + key + "')";
		callJavascript(curParentIdx, js);
	}

	private void callJavascript(int parentIdx, final String javascript) {
		// update selected item and title, then close the drawer
		mDrawerList.setItemChecked(parentIdx, true);
		mDrawerList.setSelection(parentIdx);
		setTitle(navMenuTitles[parentIdx]);

		if (curParentIdx != parentIdx) {
			// update the main content by replacing fragments
			webView.setWebChromeClient(new WebChromeClient() {
				public void onProgressChanged(WebView view, int progress) {
					MainActivity.this.setProgress(progress * 100);

				}
			});

			webView.setWebViewClient(new WebViewClient() {
				@Override
				public void onReceivedError(WebView view, int errorCode,
						String description, String failingUrl) {
					// Handle the error
				}

				@Override
				public boolean shouldOverrideUrlLoading(WebView view, String url) {
					view.loadUrl(url);
					return true;
				}

				@Override
				public void onPageFinished(WebView view, String url) {
					super.onPageFinished(view, url);
					if (Global.getCurrentLanguage() != Global.ENG)
						webView.loadUrl("javascript:translate('"
								+ Global.getCurrentLanguage() + "', null)");

					webView.loadUrl(javascript);
				}
			});

			webView.loadUrl("file:///android_asset/" + formulasLink[parentIdx]);
		} else {
			webView.loadUrl(javascript);
		}
	}

	// private void displayView(int parentIdx, int childIdx, String key) {
	// // update selected item and title, then close the drawer
	// mDrawerList.setItemChecked(parentIdx, true);
	// mDrawerList.setSelection(parentIdx);
	// setTitle(navMenuTitles[parentIdx]);
	// if (childIdx != -1)
	// mDrawerLayout.closeDrawer(mDrawerList);
	//
	// // update the main content by replacing fragments
	// Bundle bundle = new Bundle();
	// bundle.putString(SELECTED_KEY, parentIdx + ";" + childIdx + ";" + key);
	//
	// Fragment fragment = new DisplayFormulasFragment();
	// fragment.setArguments(bundle);
	// FragmentManager fragmentManager = getFragmentManager();
	// fragmentManager.beginTransaction()
	// .replace(R.id.frame_container, fragment).commit();
	//
	// }

	@Override
	public void setTitle(CharSequence title) {
		mTitle = title;
		getActionBar().setTitle(mTitle);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		getActionBar().setBackgroundDrawable(
				getResources().getDrawable(R.color.white));

		// Associate searchable configuration with the SearchView
		SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
		SearchView searchView = (SearchView) menu.findItem(R.id.action_search)
				.getActionView();
		searchView.setSearchableInfo(searchManager
				.getSearchableInfo(getComponentName()));

		searchView.setOnQueryTextListener(new OnQueryTextListener() {

			@Override
			public boolean onQueryTextSubmit(String query) {
				// TODO Auto-generated method stub
				return false;
			}

			@Override
			public boolean onQueryTextChange(String newText) {

				displaySearch(newText);
				return false;
			}

		});
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// toggle nav drawer on selecting action bar app icon/title
		if (mDrawerToggle.onOptionsItemSelected(item)) {
			return true;
		}
		// Handle action bar actions click
		switch (item.getItemId()) {
		case R.id.action_search:
			// search action
			return true;
		case R.id.action_settings:
			return true;
		case R.id.action_language:
			languageDialog.show();
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	/**
	 * When using the ActionBarDrawerToggle, you must call it during
	 * onPostCreate() and onConfigurationChanged()...
	 */

	@Override
	protected void onPostCreate(Bundle savedInstanceState) {
		super.onPostCreate(savedInstanceState);
		// Sync the toggle state after onRestoreInstanceState has occurred.
		mDrawerToggle.syncState();
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		// Pass any configuration change to the drawer toggls
		mDrawerToggle.onConfigurationChanged(newConfig);
	}

	private void changeLanguage(String language) {
		Global.setCurrentLanguage(language);

		setLocation(language);

		Intent i = getIntent();
		finish();
		startActivity(i);
	}

	private void setLocation(String language) {
		Locale locale = new Locale(language);
		Locale.setDefault(locale);
		Configuration config = new Configuration();
		config.locale = locale;
		getBaseContext().getResources().updateConfiguration(config,
				getBaseContext().getResources().getDisplayMetrics());
	}

	@Override
	public void onBackPressed() {
		if (doubleBackToExitPressedOnce) {
			super.onBackPressed();
			return;
		}

		this.doubleBackToExitPressedOnce = true;
		Toast.makeText(this, R.string.alert_exit, Toast.LENGTH_SHORT).show();

		new Handler().postDelayed(new Runnable() {

			@Override
			public void run() {
				doubleBackToExitPressedOnce = false;
			}
		}, 2000);
	}

	@Override
	protected void onPause() {
		super.onPause();
		SharedPreferences preferences = getSharedPreferences(
				"com.mathformulas", Context.MODE_PRIVATE);
		SharedPreferences.Editor editor = preferences.edit();
		editor.putString(MainActivity.LANGUAGE_KEY, Global.getCurrentLanguage());
		editor.commit();
	}
}
